package com.example.springbootdemo.service.impl;

import com.example.springbootdemo.mapper.MyLockMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @description: 继承jdk的Lock接口，实现 mysql分布式锁
 * @author: ruoan
 * @date: 2021/2/18 12:53
 */
@Service
public class GenericLock implements Lock {
    @Resource
    private MyLockMapper myLockMapper;
    /**
     * 阻塞式加锁
     */
    @Override
    public void lock() {

        while (true) {

            boolean b = tryLock();

            if (!b) {
                // 加锁失败
                try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); }

            }else{
                return;
            }

        }

    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }
    /**
     * 尝试使用 mysql加锁
     */
    @Override
    public boolean tryLock() {

        try {
            myLockMapper.addOneRecord();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void unlock() {
        myLockMapper.removeOneRecord();
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
